from beancount.core import account
from beancount.core.account import Account
from beancount.core.data import Open
from beancount.parser import printer
from datetime import datetime
import os
import json

# 设置默认的beancount文件路径
DEFAULT_BEANCOUNT_FILE = os.path.join(os.path.dirname(__file__), "ledger.beancount")

def create_beancount_account(account_name, account_type, currency, start_date=None, file_path=None):
    """
    创建一个新的beancount账户
    
    Args:
        account_name: 账户名称
        account_type: 账户类型 (Assets, Liabilities, Income, Expenses)
        currency: 货币类型
        start_date: 开始日期，格式为YYYY-MM-DD，如果为空则使用当前年份的1月1日
        file_path: beancount文件路径，如果为空则使用默认路径
        
    Returns:
        创建的Open指令对象
    """
    if file_path is None:
        file_path = DEFAULT_BEANCOUNT_FILE
        
    # 检查账户名是否已经包含账户类型前缀
    if not account_name.startswith(f"{account_type}:"):
        # 如果不包含，则添加前缀
        full_account_name = f"{account_type}:{account_name}"
    else:
        # 如果已包含，直接使用原名
        full_account_name = account_name
    
    if start_date is None:
        current_year = datetime.now().year
        start_date = datetime(current_year, 1, 1).date()
    else:
        start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
    
    # 尝试修复账户名称格式问题
    # 移除可能导致问题的空格
    full_account_name = full_account_name.replace(" ", "")
    
    # 确保每个组件都是有效的
    components = full_account_name.split(':')
    for i, component in enumerate(components):
        # 确保每个组件都是有效的标识符
        if not component.isalnum() and not all(c.isalnum() or c == '-' for c in component):
            components[i] = ''.join(c for c in component if c.isalnum() or c == '-')
    
    full_account_name = ':'.join(components)
    
    # 检查账户名是否有效
    if not account.is_valid(full_account_name):
        # 如果仍然无效，尝试使用更简单的名称
        simplified_name = f"{account_type}:{components[-1]}" if len(components) > 1 else full_account_name
        if account.is_valid(simplified_name):
            full_account_name = simplified_name
        else:
            raise ValueError(f"Invalid account name: {full_account_name}")
    
    # 检查账户是否已存在
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            if f"open {full_account_name}" in content:
                return {
                    "success": False,
                    "error": f"账户已存在: {full_account_name}",
                    "account": full_account_name
                }
    
    open_directive = Open(
        date=start_date,
        account=full_account_name,
        currencies=[currency],
        meta=None,
        booking=None
    )
    
    # 将账户指令写入文件
    try:
        with open(file_path, 'a', encoding='utf-8') as f:
            f.write(printer.format_entry(open_directive) + '\n')
        
        return {
            "success": True,
            "message": f"账户创建成功: {full_account_name}",
            "account": full_account_name,
            "directive": printer.format_entry(open_directive)
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "account": full_account_name
        }